# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/4/22
# @File   : R55_EG_CASE_EntJudicialCheck.py
# @E-mail : zhaochen@bbdservice.com

'''eof
name:申请企业司法校验（裁判文书、开庭公告）
code:R55_EG_CASE_EntJudicialCheck
tableName:
columnName:
groups:个人及企业司法校验
dependencies:EG_CASE_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import re
import datetime
from dateutil.relativedelta import relativedelta
import pandas as pd

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(table_Name):
    try:
        data = EG_CASE_DSJ['data'].get(table_Name)
        # print(data)
        if data in null_type_list:
            return None
        else:
            if isinstance(data, list) and len(data) == 0:
                return [{}]
            else:
                return data
    except:
        return None

def Formate(time):
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y-%m-%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y-%m-%d')
            except:
                try:
                    tmp = r.sub('', time)
                    if len(tmp) == 6:
                        date = datetime.datetime.strptime(tmp, '%Y%m').strftime('%Y-%m-%d')
                    elif len(tmp) >= 8:
                        date = datetime.datetime.strptime(tmp[:8], '%Y%m%d').strftime('%Y-%m-%d')
                    else:
                        date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y-%m-%d')
                except:
                    date = None
    return date

'''
【计算逻辑】
从《EG_CASE_DSJ.data.R227》中取立案时间（CASEDATE）、案号（CASENO）、公告类型（PTYPE）、原告（PLAINTIFF）、被告（PARTY）、案由（CASEREASON）、判决结果（JUDGEMENTRESULT），矩阵规则见附件-新版司法矩阵。
1）取PTYPE=15的数据，判断开庭公告的开庭时间，若申请时间-立案时间大于3年，则该条数据的Factor=1；
2）若申请时间-立案时间小于等于3年，则取PTYPE=15和PTYPE=16的数据，
 若PTYPE=15的案号能与PTYPE=16的案号匹配，则对裁判文书进行矩阵校验；
 若匹配不成功，只有开庭公告案号，则该条数据的Factor=2；只有裁判文书案号，则该条数据进行矩阵校验；
注：①矩阵中有条件通过表示该条数据的Factor=2；
②若PTYPE=16的数据，无法解析出金额，则该条数据的Factor=2；
③若PTYPE=16的数据，无法判断是否对借款人有利，则该条数据的Factor=2；
优先级：0，2，1
'''

# 处理 开庭公告
def ktggCpwsChecKPre(num):
    cases = getTable(num)
    res = []
    if cases is None:
        return None,res
    elif cases == [{}]:
        return 1,res
    else:
        ktgg_code = set()
        cpws = []
        cpws_code = set()
        flag = []
        other_ptypes = [] # 用于存非16 15的ptype

        for case in cases:
            lawstatus = case.get('LAWSTATUS')
            if lawstatus == u'无关第三方':
                res.append(1)
                continue
            ptype = case.get('PTYPE')
            if ptype in null_type_list:
                flag.append(None)
            elif ptype == '16':
                cpws.append(case)
                code = case.get('CASENO')
                if code in null_type_list:
                    flag.append(None)
                else:
                    cpws_code.add(code)
            elif ptype == '15':
                code = case.get('CASENO')
                case_date = case.get('CASEDATE')
                if code in null_type_list or Formate(case_date) is None:
                    flag.append(None)
                else:
                    case_date = datetime.datetime.strptime(Formate(case_date), '%Y-%m-%d')
                    today = datetime.datetime.now()
                    three_years_ago = today - relativedelta(years=3)#三年前
                    if case_date > today:
                        flag.append(None)
                        continue
                    if case_date >= three_years_ago:
                        ktgg_code.add(code)
                    else:
                        pass
            else:
                # 存在ptype不为15 16
                other_ptypes.append(ptype)

        if None in flag or len(other_ptypes) > 0:
            return None, res
        if len(ktgg_code) == 0:
            return cpws, res
        else:
            # ktgg有； cpws没有
            if len(cpws) == 0:
                return None, res
            # ktgg 不存在与 裁判文书中
            elif len(ktgg_code) != len(ktgg_code.intersection(cpws_code)):
                return None, res
            else:
                return cpws, res
# 提取金额
def transfer_money(money):
    """
    将金额转化成以元为单位，比如53万——>530000元
    :param money:待转换的金额,字符串
    :return:转换后的金额
    """
    uniform_money = 0.0
    money = money.replace(u",", u"").replace(u"，", u"").replace(u" ", u"")
    if money.find(u"万元") >= 0 and re.search(u"\d[.\d]*", money.replace(u"万元", u"")) is not None:
        money = money.replace(u"万元", u"")
        num = money.count(u".")
        if num > 1:
            uniform_money = float(u"".join(money.split(u".", num - 1))) * 10000
        else:
            uniform_money = float(money) * 10000
    elif re.search(u"\d[.\d]*", money.replace(u"元", u"")) is not None:
        money = money.replace(u"元", u"")
        num = money.count(u".")
        if num > 1:
            uniform_money = float(u"".join(money.split(u".", num - 1))) * 1
        else:
            uniform_money = float(money) * 1
    return uniform_money

common_used_numerals = {u'〇': 0, u'O': 0, u'零': 0, \
                        u'一': 1, u'二': 2, u'三': 3, u'四': 4, u'五': 5, u'六': 6, u'七': 7, u'八': 8, u'九': 9, u'十': 10, \
                        u'百': 100, u'千': 1000, u'万': 10000, u'亿': 100000000, \
                        u'两': 2, u'壹': 1, u'贰': 2, u'叁': 3, u'肆': 4, u'伍': 5, u'陆': 6, u'柒': 7, u'扒': 8, u'玖': 9, u'拾': 10,
                        u'佰': 100, u'仟': 1000, \
                        u'仟万': 10000000, u'千万': 10000000, u'百万': 1000000, u'佰万': 1000000, u'十万': 100000, u'拾万': 100000, \
                        u'元': 1.0, u'角': 0.1, u'分': 0.01
                        }
def split_money(dxrmb):
    """
        将中文大写金额转换成小写金额，思想：由大到小层层分割，并递归调用函数自身完成转换
        :param dxrmb: 大写金额，eg.四百二十一万五千七百三十四元
        :return: 小写金额
    """
    dxrmb = dxrmb
    units = [u"亿", u"千万", u"仟万", u"百万", u"佰万", u"十万", u"拾万", u"万", u"千", u"仟", u"佰",
             u"百", u"十", u"拾", u"元", u"角", u"分"]
    if re.search(u"元$", dxrmb) is not None:
        dxrmb = dxrmb.replace(u"元", u"").replace(u"零", u"").replace(u"〇", u"").replace(u"O", u"")
    else:
        dxrmb = dxrmb.replace(u"零", u"").replace(u"〇", u"").replace(u"O", u"")
    if dxrmb in units or dxrmb in common_used_numerals.keys():
        return common_used_numerals[dxrmb]
    for unit in units:
        dxrmb = ''.join(dxrmb).split(unit)
        if len(dxrmb) > 1:
            # print "zzzz",dxrmb[0],'yyyy',dxrmb[1]
            if len(dxrmb[0]) == 1 and len(dxrmb[1]) == 1:
                # print "进来了1"
                return common_used_numerals[dxrmb[0]] * common_used_numerals[unit] + common_used_numerals[dxrmb[1]]
            if len(dxrmb[0]) == 1 and len(dxrmb[1]) == 0:
                # print "进来了2"
                return common_used_numerals[dxrmb[0]] * common_used_numerals[unit]
            if len(dxrmb[0]) == 0 and len(dxrmb[1]) == 1:
                # print "进来了3"
                return 1 * common_used_numerals[unit] + common_used_numerals[dxrmb[1]]
            if len(dxrmb[0]) == 0 and len(dxrmb[1]) > 1:
                # print "进来了4"
                return 1 * common_used_numerals[unit] + split_money(dxrmb[1])
            if len(dxrmb[0]) == 1 and len(dxrmb[1]) > 1:
                # print "进来了5"
                return common_used_numerals[dxrmb[0]] * common_used_numerals[unit] + split_money(dxrmb[1])
            if len(dxrmb[0]) > 1 and len(dxrmb[1]) == 1:
                # print "进来了6"
                return split_money(dxrmb[0]) * common_used_numerals[unit] + common_used_numerals[dxrmb[1]]
            if len(dxrmb[0]) > 1 and len(dxrmb[1]) == 0:
                # print "进来了7"
                return split_money(dxrmb[0]) * common_used_numerals[unit]
            if len(dxrmb[0]) > 1 and len(dxrmb[1]) > 1:
                # print "进来了8"
                return split_money(dxrmb[0]) * common_used_numerals[unit] + split_money(dxrmb[1])
        else:
            continue

def getRegexAmt(entName, reKey, partH=None, party=None):
    # 给付动作
    pay = u'支付|给付|偿付|赔偿|赔付|返还|归还|偿还|清偿|补偿|' \
          u'退还|补缴|缴纳|清还|补足|付给|付清|缴清|交付|交给|交纳|退给|' \
          u'退返|返给|还给|交还|欠付|还款|退款|作价|处罚金|退赔|追缴|承担|给'
    # 涉案金额
    target = u'(?:\d*[,，]*)*\d*\.?\d*[零一二三四五六七八九十百千万亿]*[0-9零一二三四五六七八九十百千万亿]'
    # 金额单位
    unit = u'元|美元|港元|澳门元|日元|韩元|缅元|马元|新加坡元|欧元|英镑|马克|法郎|卢布|加元|新西兰元|澳元|澳大利亚元'
    # 保全动作
    preserve = u'查封|冻结|扣押|扣留'
    # 诉讼角色
    role = u'原告|被告|被申请人|申请人|上诉人|被上诉人|被执行人'

    # r14 =.* ?(?:共计 | 总计 | 合计 | 共) (【涉案金额】(?:【金额单位】)).* ?
    # r15 =.* ?(?:受理费 | 申请费 | 律师费 | 鉴定费 | 反诉费 | 律师代理费 | 审理费) (【涉案金额】(?:【金额单位】)).* ?
    # r16 =.* ?(?:已 | 应 | 尚)(【给付动作】) (【涉案金额】(?:【金额单位】)).* ?
    # r17 =.?以.? (【涉案金额】(?:【金额单位】)).?(为本金 | 为基数 | 本金 | 基数 | %)
    # r18 =.* ?【被告】.* ?(?:【给付动作】).* ?【被告】.* ? (【涉案金额】(?:【金额单位】)).* ?

    regexdict = {
        'r14':u"(?:共计|总计|合计|共)(?!和).*?(?P<money>%s(?P<unit>%s)).*?"%(target, unit),
        'r15':u'.*?(?:受理费|申请费|律师费|鉴定费|反诉费|律师代理费|审理费)(?P<money>%s(?P<unit>%s)).*?'%(target, unit),
        'r16':u'.*?(?:已|应|尚)(?:%s)(?P<money>%s(?P<unit>%s)).*?'%(pay, target, unit),
        'r17':u'.?以.?(?P<money>%s(?P<unit>%s)).?(为本金|为基数|本金|基数|%%)' %(target, unit),
        'r18':u'.*?%s.*?(?:%s).*?%s.*?(?P<money>%s(?P<unit>%s)).*?'%(party, pay,party, target, unit),
        # 增加支付违约金情况
        'r00': u'.*?支付违约金(?P<money>%s(?P<unit>%s))' %(target, unit),

        'r11':u'.*?%s.*?(?:%s).*?(?P<money>%s(?P<unit>%s)).*?' %(entName, pay, target, unit),

        'r12':u'.*?(?:%s).*?(?P<money>%s(?P<unit>%s)).*?%s.*?'%(pay, target, unit, entName),
        'r13':u'.*?(?:%s).*?%s.*?(?P<money>%s(?P<unit>%s)).*?'%(pay, entName, target, unit),
        'r21':u'.*?%s.*?(?P<money>%s(?P<unit>%s)).*?受偿.*?'%(entName, target, unit),
        'r22':u'.*?%s.*?受偿.*?(?P<money>%s(?P<unit>%s)).*?'%(entName, target, unit),
        'r31':u'.*?(?:%s).*?%s.*?(?P<money>%s(?P<unit>%s)).*?'%(preserve, entName, target, unit),
        'r32':u'.*?%s.*?(?:%s).*?(?P<money>%s(?P<unit>%s)).*?'%(entName, preserve, target, unit),
        'r33':u'.*?%s.*?(?P<money>%s(?P<unit>%s)).*?(?:%s).*?'%(entName, target, unit, preserve),
        'r41':u'.*?%s.*?(?P<money>%s(?P<unit>%s)).*?连带.*?责任.*?'%(entName, target, unit),
        'r42':u'.*?%s.*?连带.*?(?P<money>%s(?P<unit>%s)).*?'%(entName, target, unit),
        'r43':u'.*?连带赔偿.*?(?P<money>%s(?P<unit>%s)).*?'%(target, unit),
        'r011':u'.*?(?:%s).*?(?:%s).*?(?P<money>%s(?P<unit>%s)).*?'%(role, pay, target, unit),
        'r011_':u'.*?(?:%s)?.*?(?:%s).*?(?P<money>%s(?P<unit>%s)).*?'%(role, pay, target, unit),
        'r012':u'.*?(?:%s).*?(?:%s).*?(?P<money>%s(?P<unit>%s)).*?'%(pay, role, target, unit),
        'r013':u'.*?(?:%s).*?(?P<money>%s(?P<unit>%s)).*?(?:%s).*?'%(pay, target, unit, role),
        'r021':u'.*?(?:%s).*?(?P<money>%s(?P<unit>%s)).*?受偿.*?'%(role, target, unit),
        'r022':u'.*?(?:%s).*?受偿.*?(?P<money>%s(?P<unit>%s)).*?'%(role, target, unit),
        'r031':u'.*?(?:%s)(?:%s).*?(?P<money>%s(?P<unit>%s)).*?'%(preserve, role, target, unit),
        'r032':u'.*?(?:%s).*?(?:%s).*?(?P<money>%s(?P<unit>%s)).*?'%(role, preserve, target, unit),
        'r033':u'.*?(?:%s).*?(?P<money>%s(?P<unit>%s)).*?(?:%s).*?'%(role, target, unit, preserve),
        'r43_':u'.*?(?:被告)?.*?%s.*?(?:承担|赔偿)(?:连带|共同).*?'%(entName),

        'r44':u'.*?被告.*?%s.*?(?:承担|赔偿)(?:连带|共同).*?'%(entName),
        'r401':u'.*?第一项.*?',
        'r402':u'.*?第二项.*?',
        'r403':u'.*?第三项.*?',
        'r404':u'.*?上述.*?(?:承担|赔偿)(?:连带|共同)',

        'r405':u'.*?对于*被告.*?%s.*?连带.*?'%(partH),
        'r406':u'.*?%s.*?(?:%s).*?(?P<money>%s(?P<unit>%s)).*?'%(partH, pay, target, unit),
        'r407':u'.*?(?:%s).*?(?P<money>%s(?P<unit>%s)).*?%s.*?'%(pay, target, unit, partH),
        'r408':u'.*?(?:%s).*?%s.*?(?P<money>%s(?P<unit>%s)).*?'%(pay, partH, target, unit)
    }
    r = re.compile(regexdict.get(reKey))
    return r

def getAmount(entName, judgementResult, ptype, plaintiff, party):
    '''
    提取涉案金额
    :param entName:客户名称（企业）
    :param judgementResult: 判决结果
    :param ptype: 文书类型
    :param plaintiff: 原告
    :param party: 被告
    :return: 金额
    '''
    # 文本进行去空白字符；
    judgementResult = re.compile(u'\r|\n|\s').sub('', judgementResult)
    # 并过滤掉非金额类的数字
    judgementResult = re.compile(u'([0-9\\.，,]+)(?!([0-9\\.，,]+|([零一二三四五六七八九十百千万亿]*(元|美元|港元|澳门元|日元|韩元|缅元|马元|新加坡元|欧元|英镑|马克|法郎|卢布|加元|新西兰元|澳元|澳大利亚元))))').sub('', judgementResult)
    # 去掉把括号（括号包括圆括号、中括号、书名号三种
    p = re.compile(u'[（(【}《<].*?[）)】{》>]')
    entName = p.sub(u'', entName)
    plaintiff = p.sub(u'', plaintiff)
    party = p.sub(u'', party)
    partyList = []

    # Ptype为16之外的取值
    if ptype != '16':
        amountValue = None
        return amountValue
    # Ptype为16 裁判文书
    elif ptype == '16':
        if judgementResult in null_type_list:
            amountValue = None
        else:
            #用于判断判决结果中是否存在外币
            foreignCurrencyFlag = False
            # 对判决结果 去括号 同时,过滤“以XX元为本金/基数支付利息”的情况
            judgementResult =  re.compile(u'[（(【}《<].*?[）)】{》>]|(?:\d*[,，]*)*\d+\.?\d*万*元为(?:基数|本金)').sub('', judgementResult)
            Splits = re.compile(u'；|;|。').split(judgementResult)
            # 【原告人数】= 1 &【被告人数】= 1【原告】字段取值中不包含分隔符(顿号、逗号或分号：全角或半角格式）
            p = re.compile(u'[，,、；;]+')
            if p.search(plaintiff) is None and p.search(party) is None:
                onlyOneParty=True
            else:
                onlyOneParty=False
                partyList = [x for x in p.split(party) if x!='']

            # Step 1
            amountStep1 = []
            for s in Splits:
                # 由于 某句中可能存在 案件受理费的支付
                if u'案件受理费' in s:
                    continue
                if getRegexAmt(entName, 'r11').search(s):
                    #  进行 合计 共 总共 判断
                    if getRegexAmt(entName, 'r14').search(s):
                        tmp = list(getRegexAmt(entName, 'r14').finditer(s))
                        money = tmp[0].group('money')
                        unit = tmp[0].group('unit')
                        if unit != u'元':
                            foreignCurrencyFlag = True
                            break
                        if re.compile(r'[0-9]+').search(money):
                            money = transfer_money(money)
                        else:
                            money = split_money(money)
                        amountStep1.append(money)
                    else:
                        tmp = list(getRegexAmt(entName, 'r11').finditer(s))
                        for i in tmp:
                            money = i.group('money')
                            unit = i.group('unit')
                            if unit != u'元':
                                foreignCurrencyFlag = True
                                break
                            # 判断money 是不是全为中文
                            if re.compile(r'[0-9]+').search(money):
                                money = transfer_money(money)
                            else:
                                money = split_money(money)
                            amountStep1.append(money)

                        # 判断是否有附加的支付的违约金
                        tmp_sub = list(getRegexAmt(entName, 'r00').finditer(s))
                        if len(tmp_sub) != 0:
                            for i in tmp_sub:
                                money = i.group('money')
                                unit = i.group('unit')
                                if unit != u'元':
                                    foreignCurrencyFlag = True
                                    break
                                # 判断money 是不是全为中文
                                if re.compile(r'[0-9]+').search(money):
                                    money = transfer_money(money)
                                else:
                                    money = split_money(money)
                                amountStep1.append(money)
                elif getRegexAmt(entName, 'r12').search(s):
                    if getRegexAmt(entName, 'r14').search(s):
                        tmp = list(getRegexAmt(entName, 'r14').finditer(s))
                        money = tmp[0].group('money')
                        unit = tmp[0].group('unit')
                        if unit != u'元':
                            foreignCurrencyFlag = True
                            break
                        if re.compile(r'[0-9]+').search(money):
                            money = transfer_money(money)
                        else:
                            money = split_money(money)
                        amountStep1.append(money)
                    else:
                        tmp = list(getRegexAmt(entName, 'r12').finditer(s))
                        for i in tmp:
                            money = i.group('money')
                            unit = i.group('unit')
                            if unit != u'元':
                                foreignCurrencyFlag = True
                                break
                            if re.compile(r'[0-9]+').search(money):
                                money = transfer_money(money)
                            else:
                                money = split_money(money)
                            amountStep1.append(money)
                        # 判断是否有附加的支付的违约金
                        tmp_sub = list(getRegexAmt(entName, 'r00').finditer(s))
                        if len(tmp_sub) != 0:
                            for i in tmp_sub:
                                money = i.group('money')
                                unit = i.group('unit')
                                if unit != u'元':
                                    foreignCurrencyFlag = True
                                    break
                                # 判断money 是不是全为中文
                                if re.compile(r'[0-9]+').search(money):
                                    money = transfer_money(money)
                                else:
                                    money = split_money(money)
                                amountStep1.append(money)
                elif getRegexAmt(entName, 'r13').search(s):
                    if getRegexAmt(entName, 'r14').search(s):
                        tmp = list(getRegexAmt(entName, 'r14').finditer(s))
                        money = tmp[0].group('money')
                        unit = tmp[0].group('unit')
                        if unit != u'元':
                            foreignCurrencyFlag = True
                            break
                        if re.compile(r'[0-9]+').search(money):
                            money = transfer_money(money)
                        else:
                            money = split_money(money)
                        amountStep1.append(money)
                    else:
                        tmp = list(getRegexAmt(entName, 'r13').finditer(s))
                        for i in tmp:
                            money = i.group('money')
                            unit = i.group('unit')
                            if unit != u'元':
                                foreignCurrencyFlag = True
                                break
                            if re.compile(r'[0-9]+').search(money):
                                money = transfer_money(money)
                            else:
                                money = split_money(money)
                            amountStep1.append(money)
                        # 判断是否有附加的支付的违约金
                        tmp_sub = list(getRegexAmt(entName, 'r00').finditer(s))
                        if len(tmp_sub) != 0:
                            for i in tmp_sub:
                                money = i.group('money')
                                unit = i.group('unit')
                                if unit != u'元':
                                    foreignCurrencyFlag = True
                                    break
                                # 判断money 是不是全为中文
                                if re.compile(r'[0-9]+').search(money):
                                    money = transfer_money(money)
                                else:
                                    money = split_money(money)
                                amountStep1.append(money)
                elif getRegexAmt(entName, 'r21').search(s):
                    if getRegexAmt(entName, 'r14').search(s):
                        tmp = list(getRegexAmt(entName, 'r14').finditer(s))
                        money = tmp[0].group('money')
                        unit = tmp[0].group('unit')
                        if unit != u'元':
                            foreignCurrencyFlag = True
                            break
                        if re.compile(r'[0-9]+').search(money):
                            money = transfer_money(money)
                        else:
                            money = split_money(money)
                        amountStep1.append(money)
                    else:
                        tmp = list(getRegexAmt(entName, 'r21').finditer(s))
                        for i in tmp:
                            money = i.group('money')
                            unit = i.group('unit')
                            if unit != u'元':
                                foreignCurrencyFlag = True
                                break
                            if re.compile(r'[0-9]+').search(money):
                                money = transfer_money(money)
                            else:
                                money = split_money(money)
                            amountStep1.append(money)
                elif getRegexAmt(entName, 'r22').search(s):
                    if getRegexAmt(entName, 'r14').search(s):
                        tmp = list(getRegexAmt(entName, 'r14').finditer(s))
                        money = tmp[0].group('money')
                        unit = tmp[0].group('unit')
                        if unit != u'元':
                            foreignCurrencyFlag = True
                            break
                        if re.compile(r'[0-9]+').search(money):
                            money = transfer_money(money)
                        else:
                            money = split_money(money)
                        amountStep1.append(money)
                    else:
                        tmp = list(getRegexAmt(entName, 'r22').finditer(s))
                        for i in tmp:
                            money = i.group('money')
                            unit = i.group('unit')
                            if unit != u'元':
                                foreignCurrencyFlag = True
                                break
                            if re.compile(r'[0-9]+').search(money):
                                money = transfer_money(money)
                            else:
                                money = split_money(money)
                            amountStep1.append(money)
                elif getRegexAmt(entName, 'r31').search(s):
                    if getRegexAmt(entName, 'r14').search(s):
                        tmp = list(getRegexAmt(entName, 'r14').finditer(s))
                        money = tmp[0].group('money')
                        unit = tmp[0].group('unit')
                        if unit != u'元':
                            foreignCurrencyFlag = True
                            break
                        if re.compile(r'[0-9]+').search(money):
                            money = transfer_money(money)
                        else:
                            money = split_money(money)
                        amountStep1.append(money)
                    else:
                        tmp = list(getRegexAmt(entName, 'r31').finditer(s))
                        for i in tmp:
                            money = i.group('money')
                            unit = i.group('unit')
                            if unit != u'元':
                                foreignCurrencyFlag = True
                                break
                            if re.compile(r'[0-9]+').search(money):
                                money = transfer_money(money)
                            else:
                                money = split_money(money)
                            amountStep1.append(money)
                elif getRegexAmt(entName, 'r32').search(s):
                    if getRegexAmt(entName, 'r14').search(s):
                        tmp = list(getRegexAmt(entName, 'r14').finditer(s))
                        money = tmp[0].group('money')
                        unit = tmp[0].group('unit')
                        if unit != u'元':
                            foreignCurrencyFlag = True
                            break
                        if re.compile(r'[0-9]+').search(money):
                            money = transfer_money(money)
                        else:
                            money = split_money(money)
                        amountStep1.append(money)
                    else:
                        tmp = list(getRegexAmt(entName, 'r32').finditer(s))
                        for i in tmp:
                            money = i.group('money')
                            unit = i.group('unit')
                            if unit != u'元':
                                foreignCurrencyFlag = True
                                break
                            if re.compile(r'[0-9]+').search(money):
                                money = transfer_money(money)
                            else:
                                money = split_money(money)
                            amountStep1.append(money)
                elif getRegexAmt(entName, 'r33').search(s):
                    if getRegexAmt(entName, 'r14').search(s):
                        tmp = list(getRegexAmt(entName, 'r14').finditer(s))
                        money = tmp[0].group('money')
                        unit = tmp[0].group('unit')
                        if unit != u'元':
                            foreignCurrencyFlag = True
                            break
                        if re.compile(r'[0-9]+').search(money):
                            money = transfer_money(money)
                        else:
                            money = split_money(money)
                        amountStep1.append(money)
                    else:
                        tmp = list(getRegexAmt(entName, 'r33').finditer(s))
                        for i in tmp:
                            money = i.group('money')
                            unit = i.group('unit')
                            if unit != u'元':
                                foreignCurrencyFlag = True
                                break
                            if re.compile(r'[0-9]+').search(money):
                                money = transfer_money(money)
                            else:
                                money = split_money(money)
                            amountStep1.append(money)
                else:
                    amountStep1.append(None)
            if amountStep1 == [] or (len(set(amountStep1))==1 and None in amountStep1):
                amountStep1 = None
            # 存在外币 直接走人工
            if foreignCurrencyFlag:
                return None

            # Step 2 若step1中获取匹配结果返回空值 & (【原告人数】= 1 &【被告人数】= 1)
            amountStep2 = []
            if amountStep1 is None and onlyOneParty:
                for s in Splits:
                    if u'案件受理费' in s:
                        continue
                    if getRegexAmt(entName, 'r011').search(s):
                        if getRegexAmt(entName, 'r14').search(s):
                            tmp = list(getRegexAmt(entName, 'r14').finditer(s))
                            money = tmp[0].group('money')
                            unit = tmp[0].group('unit')
                            if unit != u'元':
                                foreignCurrencyFlag = True
                                break
                            if re.compile(r'[0-9]+').search(money):
                                money = transfer_money(money)
                            else:
                                money = split_money(money)
                            amountStep2.append(money)
                        else:
                            tmp = list(getRegexAmt(entName, 'r011').finditer(s))
                            for i in tmp:
                                money = i.group('money')
                                unit = i.group('unit')
                                if unit != u'元':
                                    foreignCurrencyFlag = True
                                    break
                                if re.compile(r'[0-9]+').search(money):
                                    money = transfer_money(money)
                                else:
                                    money = split_money(money)
                                amountStep2.append(money)
                    elif getRegexAmt(entName, 'r012').search(s):
                        if getRegexAmt(entName, 'r14').search(s):
                            tmp = list(getRegexAmt(entName, 'r14').finditer(s))
                            money = tmp[0].group('money')
                            unit = tmp[0].group('unit')
                            if unit != u'元':
                                foreignCurrencyFlag = True
                                break
                            if re.compile(r'[0-9]+').search(money):
                                money = transfer_money(money)
                            else:
                                money = split_money(money)
                            amountStep2.append(money)
                        else:
                            tmp = list(getRegexAmt(entName, 'r012').finditer(s))
                            for i in tmp:
                                money = i.group('money')
                                unit = i.group('unit')
                                if unit != u'元':
                                    foreignCurrencyFlag = True
                                    break
                                if re.compile(r'[0-9]+').search(money):
                                    money = transfer_money(money)
                                else:
                                    money = split_money(money)
                                amountStep2.append(money)
                    elif getRegexAmt(entName, 'r013').search(s):
                        if getRegexAmt(entName, 'r14').search(s):
                            tmp = list(getRegexAmt(entName, 'r14').finditer(s))
                            money = tmp[0].group('money')
                            unit = tmp[0].group('unit')
                            if unit != u'元':
                                foreignCurrencyFlag = True
                                break
                            if re.compile(r'[0-9]+').search(money):
                                money = transfer_money(money)
                            else:
                                money = split_money(money)
                            amountStep2.append(money)
                        else:
                            tmp = list(getRegexAmt(entName, 'r013').finditer(s))
                            for i in tmp:
                                money = i.group('money')
                                unit = i.group('unit')
                                if unit != u'元':
                                    foreignCurrencyFlag = True
                                    break
                                if re.compile(r'[0-9]+').search(money):
                                    money = transfer_money(money)
                                else:
                                    money = split_money(money)
                                amountStep2.append(money)
                    elif getRegexAmt(entName, 'r021').search(s):
                        if getRegexAmt(entName, 'r14').search(s):
                            tmp = list(getRegexAmt(entName, 'r14').finditer(s))
                            money = tmp[0].group('money')
                            unit = tmp[0].group('unit')
                            if unit != u'元':
                                foreignCurrencyFlag = True
                                break
                            if re.compile(r'[0-9]+').search(money):
                                money = transfer_money(money)
                            else:
                                money = split_money(money)
                            amountStep2.append(money)
                        else:
                            tmp = list(getRegexAmt(entName, 'r021').finditer(s))
                            for i in tmp:
                                money = i.group('money')
                                unit = i.group('unit')
                                if unit != u'元':
                                    foreignCurrencyFlag = True
                                    break
                                if re.compile(r'[0-9]+').search(money):
                                    money = transfer_money(money)
                                else:
                                    money = split_money(money)
                                amountStep2.append(money)
                    elif getRegexAmt(entName, 'r022').search(s):
                        if getRegexAmt(entName, 'r14').search(s):
                            tmp = list(getRegexAmt(entName, 'r14').finditer(s))
                            money = tmp[0].group('money')
                            unit = tmp[0].group('unit')
                            if unit != u'元':
                                foreignCurrencyFlag = True
                                break
                            if re.compile(r'[0-9]+').search(money):
                                money = transfer_money(money)
                            else:
                                money = split_money(money)
                            amountStep2.append(money)
                        else:
                            tmp = list(getRegexAmt(entName, 'r022').finditer(s))
                            for i in tmp:
                                money = i.group('money')
                                unit = i.group('unit')
                                if unit != u'元':
                                    foreignCurrencyFlag = True
                                    break
                                if re.compile(r'[0-9]+').search(money):
                                    money = transfer_money(money)
                                else:
                                    money = split_money(money)
                                amountStep2.append(money)
                    elif getRegexAmt(entName, 'r031').search(s):
                        if getRegexAmt(entName, 'r14').search(s):
                            tmp = list(getRegexAmt(entName, 'r14').finditer(s))
                            money = tmp[0].group('money')
                            unit = tmp[0].group('unit')
                            if unit != u'元':
                                foreignCurrencyFlag = True
                                break
                            if re.compile(r'[0-9]+').search(money):
                                money = transfer_money(money)
                            else:
                                money = split_money(money)
                            amountStep2.append(money)
                        else:
                            tmp = list(getRegexAmt(entName, 'r031').finditer(s))
                            for i in tmp:
                                money = i.group('money')
                                unit = i.group('unit')
                                if unit != u'元':
                                    foreignCurrencyFlag = True
                                    break
                                if re.compile(r'[0-9]+').search(money):
                                    money = transfer_money(money)
                                else:
                                    money = split_money(money)
                                amountStep2.append(money)
                    elif getRegexAmt(entName, 'r032').search(s):
                        if getRegexAmt(entName, 'r14').search(s):
                            tmp = list(getRegexAmt(entName, 'r14').finditer(s))
                            money = tmp[0].group('money')
                            unit = tmp[0].group('unit')
                            if unit != u'元':
                                foreignCurrencyFlag = True
                                break
                            if re.compile(r'[0-9]+').search(money):
                                money = transfer_money(money)
                            else:
                                money = split_money(money)
                            amountStep2.append(money)
                        else:
                            tmp = list(getRegexAmt(entName, 'r032').finditer(s))
                            for i in tmp:
                                money = i.group('money')
                                unit = i.group('unit')
                                if unit != u'元':
                                    foreignCurrencyFlag = True
                                    break
                                if re.compile(r'[0-9]+').search(money):
                                    money = transfer_money(money)
                                else:
                                    money = split_money(money)
                                amountStep2.append(money)
                    elif getRegexAmt(entName, 'r033').search(s):
                        if getRegexAmt(entName, 'r14').search(s):
                            tmp = list(getRegexAmt(entName, 'r14').finditer(s))
                            money = tmp[0].group('money')
                            unit = tmp[0].group('unit')
                            if unit != u'元':
                                foreignCurrencyFlag = True
                                break
                            if re.compile(r'[0-9]+').search(money):
                                money = transfer_money(money)
                            else:
                                money = split_money(money)
                            amountStep2.append(money)
                        else:
                            tmp = list(getRegexAmt(entName, 'r033').finditer(s))
                            for i in tmp:
                                money = i.group('money')
                                unit = i.group('unit')
                                if unit != u'元':
                                    foreignCurrencyFlag = True
                                    break
                                if re.compile(r'[0-9]+').search(money):
                                    money = transfer_money(money)
                                else:
                                    money = split_money(money)
                                amountStep2.append(money)
                    else:
                        amountStep2.append(None)
            if amountStep2 == [] or (len(set(amountStep2))==1 and None in amountStep2):
                amountStep2 = None

            if foreignCurrencyFlag:
                return None

            # Step 3 提取连带债务金额及其特殊情况
            amountStep3 = []
            if amountStep1 is None and amountStep2 is None:
                for idx, s in enumerate(Splits):
                    if u'案件受理费' in s:
                        continue
                    if getRegexAmt(entName, 'r41').search(s):
                        tmp_result = []
                        tmp = list(getRegexAmt(entName, 'r41').finditer(s))
                        for i in tmp:
                            money = i.group('money')
                            unit = i.group('unit')
                            if unit != u'元':
                                foreignCurrencyFlag = True
                                break
                            # 判断money 是不是全为中文
                            if re.compile(r'[0-9]+').search(money):
                                money = transfer_money(money)
                            else:
                                money = split_money(money)
                            tmp_result.append(money)
                        if tmp_result != []:
                            amountStep3.append(sum(tmp_result))
                    elif getRegexAmt(entName, 'r42').search(s):
                        tmp_result = []
                        tmp = list(getRegexAmt(entName, 'r42').finditer(s))
                        for i in tmp:
                            money = i.group('money')
                            unit = i.group('unit')
                            if unit != u'元':
                                foreignCurrencyFlag = True
                                break
                            # 判断money 是不是全为中文
                            if re.compile(r'[0-9]+').search(money):
                                money = transfer_money(money)
                            else:
                                money = split_money(money)
                            tmp_result.append(money)
                        if tmp_result != []:
                            amountStep3.append(sum(tmp_result))
                    elif getRegexAmt(entName, 'r43_').search(s):
                        r011 = getRegexAmt(entName, 'r011_')
                        r012 = getRegexAmt(entName, 'r012')
                        r013 = getRegexAmt(entName, 'r013')
                        if getRegexAmt(entName, 'r401').search(s):
                            tmp_result = []
                            for r in [r011, r012, r013]:
                                # 匹配第一部分 splits[0]
                                tmp = list(r.finditer(Splits[0]))
                                if len(tmp) == 0:
                                    continue
                                else:
                                    if getRegexAmt(entName, 'r14').search(Splits[0]):
                                        tmp = list(getRegexAmt(entName, 'r14').finditer(Splits[0]))
                                        money = tmp[0].group('money')
                                        unit = tmp[0].group('unit')
                                        if unit != u'元':
                                            foreignCurrencyFlag = True
                                            break
                                        if re.compile(r'[0-9]+').search(money):
                                            money = transfer_money(money)
                                        else:
                                            money = split_money(money)
                                        tmp_result.append(money)
                                        break
                                    else:
                                        for i in tmp:
                                            money = i.group('money')
                                            unit = i.group('unit')
                                            if unit != u'元':
                                                foreignCurrencyFlag = True
                                                break
                                            if re.compile(r'[0-9]+').search(money):
                                                money = transfer_money(money)
                                            else:
                                                money = split_money(money)
                                            tmp_result.append(money)
                                        break
                            if tmp_result != []:
                                amountStep3.append(sum(tmp_result))
                        elif getRegexAmt(entName, 'r402').search(s):
                            tmp_result = []
                            for r in [r011, r012, r013]:
                                # 匹配第二部分 splits[1]
                                tmp = list(r.finditer(Splits[1]))
                                if len(tmp) == 0:
                                    continue
                                else:
                                    if getRegexAmt(entName, 'r14').search(Splits[1]):
                                        tmp = list(getRegexAmt(entName, 'r14').finditer(Splits[1]))
                                        money = tmp[0].group('money')
                                        unit = tmp[0].group('unit')
                                        if unit != u'元':
                                            foreignCurrencyFlag = True
                                            break
                                        if re.compile(r'[0-9]+').search(money):
                                            money = transfer_money(money)
                                        else:
                                            money = split_money(money)
                                        tmp_result.append(money)
                                        break
                                    else:
                                        for i in tmp:
                                            money = i.group('money')
                                            unit = i.group('unit')
                                            if unit != u'元':
                                                foreignCurrencyFlag = True
                                                break
                                            if re.compile(r'[0-9]+').search(money):
                                                money = transfer_money(money)
                                            else:
                                                money = split_money(money)
                                            tmp_result.append(money)
                                        break
                            if tmp_result != []:
                                amountStep3.append(sum(tmp_result))
                        elif getRegexAmt(entName, 'r403').search(s):
                            tmp_result = []
                            for r in [r011, r012, r013]:
                                # 匹配第三部分 splits[2]
                                tmp = list(r.finditer(Splits[2]))
                                if len(tmp) == 0:
                                    continue
                                else:
                                    if getRegexAmt(entName, 'r14').search(Splits[2]):
                                        tmp = list(getRegexAmt(entName, 'r14').finditer(Splits[2]))
                                        money = tmp[0].group('money')
                                        unit = tmp[0].group('unit')
                                        if unit != u'元':
                                            foreignCurrencyFlag = True
                                            break
                                        if re.compile(r'[0-9]+').search(money):
                                            money = transfer_money(money)
                                        else:
                                            money = split_money(money)
                                        tmp_result.append(money)
                                        break
                                    else:
                                        for i in tmp:
                                            money = i.group('money')
                                            unit = i.group('unit')
                                            if unit != u'元':
                                                foreignCurrencyFlag = True
                                                break
                                            if re.compile(r'[0-9]+').search(money):
                                                money = transfer_money(money)
                                            else:
                                                money = split_money(money)
                                            tmp_result.append(money)
                                        break
                            if tmp_result != []:
                                amountStep3.append(sum(tmp_result))
                        elif getRegexAmt(entName, 'r44').search(s):
                            # 当F_i匹配r44返回True时，假设此时i = g
                            tmp_result = []
                            for s in Splits[:idx+1]:
                                if r011.search(s):
                                    # 查找合计、共、等字段
                                    if getRegexAmt(entName, 'r14').search(s):
                                        tmp = list(getRegexAmt(entName, 'r14').finditer(s))
                                        money = tmp[0].group('money')
                                        unit = tmp[0].group('unit')
                                        if unit != u'元':
                                            foreignCurrencyFlag = True
                                            break
                                        if re.compile(r'[0-9]+').search(money):
                                            money = transfer_money(money)
                                        else:
                                            money = split_money(money)
                                        tmp_result.append(money)
                                    else:
                                        tmp = list(r011.finditer(s))
                                        for i in tmp:
                                            money = i.group('money')
                                            unit = i.group('unit')
                                            if unit != u'元':
                                                foreignCurrencyFlag = True
                                                break
                                            if re.compile(r'[0-9]+').search(money):
                                                money = transfer_money(money)
                                            else:
                                                money = split_money(money)
                                            tmp_result.append(money)
                                elif r012.search(s):
                                    # 查找合计、共、等字段
                                    if getRegexAmt(entName, 'r14').search(s):
                                        tmp = list(getRegexAmt(entName, 'r14').finditer(s))
                                        money = tmp[0].group('money')
                                        unit = tmp[0].group('unit')
                                        if unit != u'元':
                                            foreignCurrencyFlag = True
                                            break
                                        if re.compile(r'[0-9]+').search(money):
                                            money = transfer_money(money)
                                        else:
                                            money = split_money(money)
                                        tmp_result.append(money)
                                    else:
                                        tmp = list(r012.finditer(s))
                                        for i in tmp:
                                            money = i.group('money')
                                            unit = i.group('unit')
                                            if unit != u'元':
                                                foreignCurrencyFlag = True
                                                break
                                            if re.compile(r'[0-9]+').search(money):
                                                money = transfer_money(money)
                                            else:
                                                money = split_money(money)
                                            tmp_result.append(money)
                                elif r013.search(s):
                                    if getRegexAmt(entName, 'r14').search(s):
                                        tmp = list(getRegexAmt(entName, 'r14').finditer(s))
                                        money = tmp[0].group('money')
                                        unit = tmp[0].group('unit')
                                        if unit != u'元':
                                            foreignCurrencyFlag = True
                                            break
                                        if re.compile(r'[0-9]+').search(money):
                                            money = transfer_money(money)
                                        else:
                                            money = split_money(money)
                                        tmp_result.append(money)
                                    else:
                                        tmp = list(r013.finditer(s))
                                        for i in tmp:
                                            money = i.group('money')
                                            unit = i.group('unit')
                                            if unit != u'元':
                                                foreignCurrencyFlag = True
                                                break
                                            if re.compile(r'[0-9]+').search(money):
                                                money = transfer_money(money)
                                            else:
                                                money = split_money(money)
                                            tmp_result.append(money)
                            if tmp_result != []:
                                amountStep3.append(sum(tmp_result))

                    else:
                        if onlyOneParty is False and len(partyList) > 1:
                            for p in partyList:
                                tmp_result = []
                                if getRegexAmt(entName,'r405', partH=p).search(s) and p != entName:
                                    for fv in Splits[:idx+1]:
                                        if getRegexAmt(entName, 'r406', partH=p).search(fv):
                                            tmp = list(getRegexAmt(entName, 'r406', partH=p).finditer(fv))
                                            for i in tmp:
                                                money = i.group('money')
                                                unit = i.group('unit')
                                                if unit != u'元':
                                                    foreignCurrencyFlag = True
                                                    break
                                                if re.compile(r'[0-9]+').search(money):
                                                    money = transfer_money(money)
                                                else:
                                                    money = split_money(money)
                                                tmp_result.append(money)
                                        elif getRegexAmt(entName, 'r407', partH=p).search(fv):
                                            tmp = list(getRegexAmt(entName, 'r407', partH=p).finditer(fv))
                                            for i in tmp:
                                                money = i.group('money')
                                                unit = i.group('unit')
                                                if unit != u'元':
                                                    foreignCurrencyFlag = True
                                                    break
                                                if re.compile(r'[0-9]+').search(money):
                                                    money = transfer_money(money)
                                                else:
                                                    money = split_money(money)
                                                tmp_result.append(money)
                                        elif getRegexAmt(entName, 'r408', partH=p).search(fv):
                                            tmp = list(getRegexAmt(entName, 'r408', partH=p).finditer(fv))
                                            for i in tmp:
                                                money = i.group('money')
                                                unit = i.group('unit')
                                                if unit != u'元':
                                                    foreignCurrencyFlag = True
                                                    break
                                                if re.compile(r'[0-9]+').search(money):
                                                    money = transfer_money(money)
                                                else:
                                                    money = split_money(money)
                                                tmp_result.append(money)
                                        else:
                                            continue
                                if tmp_result != []:
                                    amountStep3.append(sum(tmp_result))
                        else:
                            amountStep3.append(None)
            if amountStep3 == [] or (len(set(amountStep3))==1 and None in amountStep3):
                amountStep3 = None

            if foreignCurrencyFlag:
                return None

            #返回结果
            if amountStep1 is None and amountStep2 is None and amountStep3 is None:
                amountValue = None
            else:
                if amountStep1 is None:
                    amountStep1 = 0.0
                else:
                    amountStep1 = sum([amount for amount in amountStep1 if amount !=None])
                if amountStep2 is None:
                    amountStep2 = 0.0
                else:
                    amountStep2 = sum([amount for amount in amountStep2 if amount != None])
                if amountStep3 is None:
                    amountStep3 = 0.0
                else:
                    amountStep3 = sum([amount for amount in amountStep3 if amount != None])

                amountValue = amountStep1 + amountStep2 + amountStep3

        return amountValue

# 提取 重要案由
def caseReasonExtraction(casereason, pdesc=None, docuclass=None):

    if ((u'农村房屋买卖' not in casereason) and \
        (u'小额借款' in casereason or u'民间借贷' in casereason or u'企业借贷' in casereason or u'生命权' in casereason or u'建设用地' in casereason or u'房地产开发' in casereason \
        or u'商品房买卖' in casereason or u'典当' in casereason or u'船舶买卖' in casereason or u'不正当竞争' in casereason \
        or u'出资人权益' in casereason or u'公司盈余' in casereason or u'股东损害公司' in casereason \
        or u'民间借贷' in casereason or u'房屋买卖' in casereason)
        ) \
        or (u'房屋租赁合同' in casereason and (u'生产场所' in pdesc or u'生产场地' in pdesc or u'生产用地' in pdesc \
                    or u'经营场所' in pdesc or u'经营场地' in pdesc or u'经营用地' in pdesc)):
        return u'重要案由'
    elif docuclass == '4':
        return u'重要案由'
    elif caseReasonImportant(casereason):
        return u'重要案由'
    elif casereason in null_type_list or (u'房屋租赁合同' in casereason and pdesc in null_type_list):
        return u'无法判断'
    else:
        return u'一般案由'

def caseReasonImportant(casereason):
    '''
    处理 case reason前，先对其去除字符处理
    :param casereason: 案由
    :return: 是否为重要案由
    '''
    #不满足情况的 xx权
    #(?!健康|身体|姓名|肖像|名誉|荣誉|隐私|婚姻自主|人身自主|一般人格|物|所有|业主(?:专有|共有|撤销|知情)|优先购买)
    #(?!用益物|海域使用|探矿|采矿|取水|养殖|捕捞|土地承包经营|用地使用|宅基地使用|地役)
    #(?!抵押|质押|产质|转质|最高额质|票据质|债券质|存单质|仓单质|提单质|股权质|基金份额质|知识产权质|应收账款质)
    #(?!留置|取回|证券|破产债|股票|基金|追索|船舶|出资人|别除|求偿|请求|海事债)
    #(?!侵权责任纠纷|网络侵权责任纠纷|其他侵权责任纠纷)

    # result = None
    casereason = re.compile(r'[\s+\.\!\/_,$%^*(+\"\']+|[+——！，。？、~@#￥%……&*（）]+').sub('',casereason)

    pattern1 = u'\w*(?:健康|身体|姓名|肖像|名誉|荣誉|隐私|知情(?:同意)?|婚姻自主|人身自主|(?:一般)?人格|物|所有|业主(?:专有|共有|撤销|知情)|优先(?:购买)?|用益物|海域使用|探矿|采矿|取水|养殖|捕捞|土地承包经营|用地使用|宅基地使用|地役|抵押|质押|产质|转质|最高额质|票据质|债券质|存单质|仓单质|提单质|股权质|基金份额质|知识产权质|应收账款质|留置|取回|证券|破产债|股票|基金|追索|船舶|出资人|别除|求偿|追偿|请求|海事债|代位|撤销|不良债|担保追偿|追收债|债券|监护|探望|抵销)权\w*'
    pattern2 = u'\w*(?:(?:侵权|网络侵权|其他侵权|公司债权人利益)责任纠纷|共有权确认|债权债务|优先受偿权纠纷|股权转让|债权转让|组织成员权益|债权转股权|执行知识产权仲裁|国债权利)\w*'
    pattern = pattern1 + '|' + pattern2
    # 01 知识产权合同纠纷
    pattern0101 = u'\w*(?:委托创作|合作创作|创造|创作|出版|表演|音像|广播|电视(?!购物)|著作|计算机软件)\w*(?:合同)纠纷'
    pattern0102 = u'\w*(?:商标|植物新品种|集成电路布图|技术秘密|经营秘密|技术|企业名称|商号|网络域名)\w*(?:使用许可|转让|使用|育种|实施许可|设计|创作|让与|注册|代理)\w*(?:合同)纠纷'
    pattern0103 = u'\w*(?:技术(?:委托开发|合作开发|转化|咨询|服务|培训|中介|进口|出口)\w*(?:合同)纠纷)|(?:\w*技术成果完成\w*)|\w*侵害网络域名纠纷|\w*(?:特许经营|特殊标志)(?:合同)纠纷'

    # 02 知识产权权属、侵权纠纷  （已经完成）
    #著作权权属、侵权纠纷 商标权权属、侵权纠纷
    pattern0201 = u'\w*(?:侵害|侵犯)\w+权(?:纠纷)?|(?:\w+权(?:转让|质押|使用|许可使用)?\w*合同纠纷)|\w+权权?属?(?:纠纷)?'
    #专利权权属、侵权纠纷
    pattern0202 = u'(?:\w*(?:假冒)?\w*专利权?\w*(?:纠纷)?)|(?:\w*(?:发明创造)?发明人设计人\w*权?纠纷)'
    #植物新品种权权属侵权纠纷
    # 发现权纠纷 发明权纠纷 其他科技成果权纠纷 网络域名权属纠纷
    #todo 侵害网络域名纠纷 侵害企业名称（商号）权纠纷
    # 03	不正当竞争纠纷
    pattern0301 = u'\w*(?:仿冒|伪造|擅自使用|冒用)\w*(?:名称|包装|装潢|标志|产地|姓名)\w*(?:纠纷)?'
    pattern0302 = u'\w*(?:虚假宣传|有奖销售|诋毁|差别待遇|垄断(?:定价|协议)?|掠夺(?:定价)?|(?:拒绝|限定|捆绑)交易|侵害(?:技术|经营|商业)秘密)\w*(?:纠纷)?'

    if re.compile(pattern).search(casereason):
        return False
    else:
        if re.compile(pattern0201).search(casereason):
            # result = re.compile(pattern0201).findall(casereason)
            return True
        elif re.compile(pattern0202).search(casereason):
            # result = re.compile(pattern0202).findall(casereason)
            return True
        elif re.compile(pattern0101).search(casereason):
            # result = re.compile(pattern0101).findall(casereason)
            return True
        elif re.compile(pattern0102).search(casereason):
            # result = re.compile(pattern0102).findall(casereason)
            return True
        elif re.compile(pattern0103).search(casereason):
            # result = re.compile(pattern0103).findall(casereason)
            return True
        elif re.compile(pattern0301).search(casereason):
            # result = re.compile(pattern0301).findall(casereason)
            return True
        elif re.compile(pattern0302).search(casereason):
            # result = re.compile(pattern0302).findall(casereason)
            return True
        else:
            return False
    # print(casereason,'>>>结果: ', result)

# 是否有利
def getRegexBft(entName, reKey):
    # 给付动作
    pay = u'支付|给付|偿付|赔偿|赔付|返还|归还|偿还|清偿|补偿|' \
          u'退还|补缴|缴纳|清还|补足|付给|付清|缴清|交付|交给|交纳|退给|' \
          u'退返|返给|还给|交还|欠付|还款|退款|作价|处罚金|退赔|追缴|承担|给'
    # 涉案金额
    target = u'(?:\d*[,，]*)*\d*\.?\d*[零一二三四五六七八九十百千万亿]*[0-9零一二三四五六七八九十百千万亿]'
    # 金额单位
    unit = u'元|美元|港元|澳门元|日元|韩元|缅元|马元|新加坡元|欧元|英镑|马克|法郎|卢布|加元|新西兰元|澳元|澳大利亚元'
    # 保全动作
    preserve = u'查封|冻结|扣押|扣留'
    # 诉讼角色
    role = u'原告|被告|被申请人|申请人|上诉人|被上诉人|被执行人'

    regexDict = {
        # 裁定不予立案
        'r01': u'.*?对?.*?不予(?:立案|受理|采纳)',
        # 驳回原告起诉 # 先判断驳回管辖权异议
        'r02': u'.*?驳回(?:原告|起诉人)?.*?(?:起诉|申请)|.*?原告.*?被告.*?请求不予支持|.*?对?.*?决定不予执行|.*?驳回.*?(?<!其他)(?:诉讼请求|异议请求|异议)',
        # 同意原告撤诉
        'r03': u'.*?(?:准许|准予).*?撤诉.*?|.*?(?:准许|准予).*?(?:撤回|诉回|撤销).*?(?:起诉|上诉|复议|诉讼|申请)|.*?(?:本案)?按.*?(?:撤诉|撤回起诉|放弃诉讼|撤回上诉)(?:处理)?',
        # 'r03': r'.*?(?:准许|准予).*?(?:撤诉|撤回.*?起诉|撤回.*?上诉|诉回.*?起诉)|.*?本案按.*?(?:撤诉|撤回起诉)处理',
        # 裁定如下：准许原告华强方特（深圳）动漫有限公司撤回对被告厦门市翔安区欣四季红生鲜店的起诉
        # 裁定同意原告的保全申请
        'r04': u'.*?(查封|冻结|扣押|扣划|提取|划拨|拍卖).*?(?:财产|人民币|收入)?',
        # 裁定驳回原告的保全申请
        'r05': u'.*?解除.*?(?:冻结|查封|扣押|扣划|提取|划拨|拍卖).*?(?:财产|人民币)',
        # 裁定同意被告的管辖权异议
        'r06': u'.*?(?:被告)?管辖权.*?异议成立',
        # 裁定驳回被告的管辖权异议
        'r07': u'.*?驳回.*?管辖权.*?异议',
        # 双方达成调解协议
        # 对上述调解协议依法确认其法律效力,
        # 协议：一、被告安徽金孔雀温泉旅游度假村有。双方当事人一致同意本调解协议自双方在调解协议上签名或捺印后即具有法律效力
        # 如下调解协议：李伟下欠任士伟
        # 上述调解协议合法有效。双方
        # 申请人王明东与申请人刘磊调解协议有效，本院予以确认
        # （2013）沅民一初字第863号民事调解书确定的义务和解履行完毕。本
        # 确认上述调解协议有效，一方当事人拒绝履行或者未全部履行的，对方当事人可
        'r08': u'.*?达成的?调解协议|.*?履行.*?调解书.*?义务|.*?调解(?:协议|书).*?(?:确认.*?法律效力|合法有效|有效)|^(?:协议|如下调解协议).*?',
        # 裁定准予行政处罚 (有撤销的先判断)
        'r09': u'.*?对.*?行政处罚.*?执行|.*?(?<!不准许)(?:强制)?执行.*?行政处罚',
        # 裁定本案中止诉讼或执行 (有撤销先判断)
        'r10': u'.*?(?<!不)中止.*?(?:执行|诉讼|审理)',
        # 裁定本案终结诉讼或执行
        'r11': u'.*?终结.*?(?:执行|诉讼|公示催告)|.*?执行.*?终结',
        # 驳回原告的上诉/申诉/复议/再审申请并维持原裁判
        'r12': u'.*?驳回上诉.*?维持(?:原判|原裁定)|.*?驳回.*?(?:申诉|复议|再审申请)',
        # 裁定撤销原裁判并对本案提审/指令再审/发回重审
        'r13': u'.*?撤销.*?(?:移交|移送|交接|发回).*?(?:审理|判决|重审|重新审批)|.*?本院(?:提审|再审)|.*?撤销.*?裁定.*?指令.*?审理',
        # 裁定撤销原裁判并无其他裁判 and if 条件中含有金额 则不按该方式处理
        'r14': u'.*?撤销.*?(?:判决)',
        # 判决支持原告的部分诉讼请求且提及客户相关义务
        'r15': u'.*?驳回.*?其他诉讼请求.*?履行.*?义务',

        'r11_':u'.*?(?:%s).*?(?:%s(?:%s)).*?'%(pay, target, unit),
        'r011': u'.*?(?:%s).*?(?:%s).*?(?:%s(?:%s)).*?'%(role, pay, target, unit),
        'r012': u'.*?(?:%s).*?(?:%s).*?(?:%s(?:%s)).*?'%(pay, role, target, unit),
        'r013': u'.*?(?:%s).*?(?:%s(?:%s)).*?(?:%s).*?'%(pay, target, unit, role),
        'r021': u'.*?(?:%s).*?(?:%s(?:%s)).*?受偿.*?'%(role, target, unit),
        'r022': u'.*?(?:%s).*?受偿.*?(?:%s(?:%s)).*?'%(role, target, unit),
        'r21':u'.*?%s.*?(?:%s(?:%s)).*?受偿.*?'%(entName, target, unit),
        'r22':u'.*?%s.*?受偿.*?(?:%s(?:%s)).*?'%(entName, target, unit),
        # 'r31':u'.*?(?:{0}){1}.*?(?P<money>{2}(?:{3})).*?'.format(preserve, entName, target, unit),
        # 'r32':u'.*?{0}.*?(?:{1}).*?(?P<money>{2}(?:{3})).*?'.format(entName, preserve, target, unit),
        # 'r33':u'.*?{0}.*?(?P<money>{1}(?:{2})).*?(?:{3}).*?'.format(entName, target, unit, preserve),
        'r41':u'.*?%s.*?(?:%s(?:%s)).*?连带.*?责任.*?'%(entName, target, unit),
        'r42':u'.*?%s.*?连带.*?(?:%s(?:%s)).*?'%(entName, target, unit),
        # 'r43':u'.*?连带赔偿.*?(?P<money>{0}(?:{1})).*?'.format(target, unit),
        'r91':u'.*?被告%s.*?不承担.*?责任'%(entName)
    }
    return re.compile(regexDict[reKey])

def benefitExtraction(entName, judgementResult, plaintiff=None, party=None):
    '''
    是否有利对于客户不同的角色  1为有利 0为不利-1为无法判断 2为撤诉
    :param entName: 该客户名称（企业）
    :param judgementResult: 判决结果
    :param plaintiff: 原告
    :param party: 被告
    :return: 对客户是否有利
    '''
    result = None
    code = None
    # 文本进行去空白字符；
    judgementResult = re.compile(u'\r|\n|\s').sub(u'', judgementResult)
    # 去掉把括号（括号包括圆括号、中括号、书名号三种
    p = re.compile(u'[（(【}《<].*?[）)】{》>]')
    judgementResult = p.sub(u'', judgementResult)
    entName = p.sub(u'', entName)
    plaintiff = p.sub(u'', plaintiff)
    party = p.sub(u'', party)

    # 考虑是否要去除所有标点符号？

    if getRegexBft(entName, 'r01').search(judgementResult):
        result = u'裁定不予立案'
        code = 1
    elif getRegexBft(entName, 'r07').search(judgementResult):
        result = u'裁定驳回被告的管辖权异议'
        code = 7
    elif getRegexBft(entName, 'r02').search(judgementResult):
        result = u'驳回原告起诉'
        code = 2
    elif getRegexBft(entName, 'r03').search(judgementResult):
        result = u'同意原告撤诉'
        code = 3
    elif getRegexBft(entName, 'r05').search(judgementResult):
        result = u'裁定驳回原告的保全申请'
        code = 5
    elif getRegexBft(entName, 'r04').search(judgementResult):
        result = u'裁定同意原告的保全申请'
        code = 4
    elif getRegexBft(entName, 'r06').search(judgementResult):
        result = u'裁定同意被告的管辖权异议'
        code = 6
    elif getRegexBft(entName, 'r08').search(judgementResult):
        result = u'双方达成调解协议'
        code = 8
    elif getRegexBft(entName, 'r10').search(judgementResult):
        result = u'裁定本案中止诉讼或执行'
        code = 10
    elif getRegexBft(entName, 'r11').search(judgementResult):
        result = u'裁定本案终结诉讼或执行'
        code = 11
    elif getRegexBft(entName, 'r12').search(judgementResult):
        result = u'驳回原告的上诉/申诉/复议/再审申请并维持原裁判'
        code = 12
    elif getRegexBft(entName, 'r13').search(judgementResult):
        result = u'裁定撤销原裁判并对本案提审/指令再审/发回重审'
        code = 13
    #注意要补充
    elif getRegexBft(entName, 'r14').search(judgementResult):
        result = u'裁定撤销原裁判并无其他裁判'
        code = 14
    elif getRegexBft(entName, 'r15').search(judgementResult):
        if getRegexBft(entName, 'r91').search(judgementResult):
            code = 91
            result = u'判决客户不承担连带责任'
        else:
            code = 15
            result = u'判决支持原告的部分诉讼请求且提及客户相关义务'
    elif getRegexBft(entName, 'r09').search(judgementResult):
        result = u'裁定准予行政处罚'
        code = 9

    else:
        # 并过滤掉非金额类的数字
        judgementResult = re.compile(
            u'([0-9\\.，,]+)(?!([0-9\\.，,]+|([零一二三四五六七八九十百千万亿]*(元|美元|港元|澳门元|日元|韩元|缅元|马元|新加坡元|欧元|英镑|马克|法郎|卢布|加元|新西兰元|澳元|澳大利亚元))))').sub(
            '', judgementResult)
        if getRegexBft(entName, 'r91').search(judgementResult):
            result = u'判决客户不承担连带责任'
            code = 91
        elif getRegexBft(entName, 'r41').search(judgementResult) or getRegexBft(entName,'r42').search(judgementResult):
            result = u'判决客户承担连带责任'
            code = 41
        elif getRegexBft(entName, 'r11_').search(judgementResult) or getRegexBft(entName, 'r011').search(judgementResult) \
                or getRegexBft(entName, 'r012').search(judgementResult) or getRegexBft(entName, 'r013').search(judgementResult) \
                or getRegexBft(entName, 'r021').search(judgementResult) or getRegexBft(entName, 'r022').search(judgementResult) \
                or getRegexBft(entName, 'r21').search(judgementResult) or getRegexBft(entName, 'r22').search(judgementResult):
            result = u'赔偿支付'
            code = 99
        else:
            result = None
            code = None

    # print(result)
    # 对客户是否有利进行判断 1为有利 0为不利-1为无法判断 2为撤诉
    if code == 1:
        if entName in plaintiff:
            return 0
        elif entName in party:
            return 1
        else:
            return -1
    elif code == 2:
        if entName in plaintiff:
            return 0
        elif entName in party:
            return 1
        else:
            return -1
    # 撤诉
    elif code == 3:
        # if entName in plaintiff:
        #     return -1
        # elif entName in party:
        #     return 1
        # else:
        #     return -1
        return 2
    elif code == 4:
        if entName in plaintiff:
            return 1
        elif entName in party:
            return 0
        else:
            return -1
    elif code == 5:
        if entName in plaintiff:
            return 0
        elif entName in party:
            return 1
        else:
            return -1
    elif code == 6:
        if entName in plaintiff:
            return 0
        elif entName in party:
            return 1
        else:
            return -1
    elif code == 7:
        if entName in plaintiff:
            return 1
        elif entName in party:
            return 0
        else:
            return -1
    elif code == 8:
        return -1
    elif code == 9:
        if entName in plaintiff or entName in party:
            return 0
        else:
            return -1
    elif code == 10 or code == 11:
        return -1
    elif code == 12:
        if entName in plaintiff:
            return 0
        elif entName in party:
            return 1
        else:
            return -1
    elif code == 13 or code == 14:
        return -1
    elif code == 15:
        if entName in plaintiff:
            return 1
        elif entName in party:
            return 0
        else:
            return -1
    elif code == 91:
        return 1
    elif code == 41:
        return 0
    elif code == 99:
        if entName in plaintiff:
            return 1
        elif entName in party:
            return 0
        else:
            return -1
    else:
        return -1

# 是否结案
def caseSettled(judgementResult):
    judgement = re.compile(u'[\s+\.\!\/_,$%^*(+\"\']+|[+——！，。？、~@#￥%……&*（）]+').sub('', judgementResult)

    pattern01 = u'.*?撤销.*?(?:移交|移送|交接|发回).*?(?:审理|判决|重审|重新审批)|.*?本院(?:提审|再审)|.*?撤销.*?裁定.*?指令.*?审理|.*?转为.*?普通程序|.*?本案.*?移送.*?法院'
    if u'冻结' in judgement or u'提取' in judgement or u'扣划' in judgement or u'查封' in judgement \
            or u'扣押' in judgement or u'拍卖' in judgement or u'变卖' in judgement:
        return u'未结案'
    elif re.compile(pattern01).search(judgement):
        return u'未结案'
    else:
        return u'结案'


# def R55_EG_CASE_EntJudicialCheck():
#     '''
#     公告类型（PTYPE）；16
#     立案时间（CASEDATE）；
#     被告（PARTY）；
#     原告（PLAINTIFF）；
#     公告内容（PDESC）；
#     案件标题/标的名称（TARGET）；案由（CASEREASON）；案件性质（DOCUCLASS）
#     判决结果（JUDGEMENTRESULT）
#
#     公司名称（ENTNAME）；
#     :return: 0 拒绝 1 通过 2 人工
#     '''
#     cpwss = ktggCpwsChecKPre()
#
#     if cpwss is None:
#         # return u'人工'
#         print 'cpws 为空'
#         return 2
#     elif cpwss == 1:
#         # return u'通过'
#         return 1
#     else:
#         # 司法矩阵 时间节点
#         last_year_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(years=i)).strftime('%Y-%m-%d') \
#                           for i in [0, 1, 2]]
#         last_year_list.append((datetime.datetime.now() - pd.tseries.offsets.DateOffset(months=6)).strftime('%Y-%m-%d'))
#         last_year_list = sorted(last_year_list, reverse=True)
#
#         result = []
#         # 对每一条裁判文书 走司法矩阵
#         for cpws in cpwss:
#             ent_name = cpws.get('ENTNAME')
#             case_date = cpws.get('CASEDATE')
#             party = cpws.get('PARTY')
#             plaintiff = cpws.get('PLAINTIFF')
#             target = cpws.get('TARGET')
#             case_reason = cpws.get('CASEREASON')
#             doc_class = cpws.get('DOCUCLASS')
#             judgement_result = cpws.get('JUDGEMENTRESULT')
#             ptype = cpws.get('PTYPE')
#             pdesc = cpws.get('PDESC')
#             # print ent_name, judgement_result
#             # 如果其中有一个为空
#             if ent_name in null_type_list or case_date in null_type_list or party in null_type_list \
#                 or party in null_type_list or plaintiff in null_type_list or target in null_type_list \
#                 or case_reason in null_type_list or doc_class in null_type_list or judgement_result in null_type_list \
#                 or Formate(case_date) is None or Formate(case_date) > last_year_list[0] or pdesc in null_type_list:
#                 result.append(None)
#             else:
#                 try:
#                     amount = getAmount(entName=ent_name, judgementResult=judgement_result,
#                                        ptype=ptype, plaintiff=plaintiff, party=party)
#
#                     important_reason = caseReasonExtraction(casereason=case_reason, pdesc=pdesc, docuclass=doc_class)
#
#                     ent_benefit = benefitExtraction(entName=ent_name, judgementResult=judgement_result,
#                                                     plaintiff=plaintiff, party=party)
#
#                     case_settled = caseSettled(judgementResult=judgement_result)
#
#                     print u'测试结果:'
#                     print u'金额:',amount,u'重要案由:',important_reason, u'是否有利:',ent_benefit,u'是否结案:',case_settled
#
#                     # ent_benefit== 2 撤诉
#                     if ent_benefit == 2:
#                         # 通过
#                         result.append(1)
#                     elif case_settled == u'未结案' or important_reason == u'无法判断' or ent_benefit == -1 or amount is None:
#                         # 人工  无法判断
#                         result.append(2)
#                     else:
#                         # 走司法矩阵
#                         case_date = Formate(case_date)
#                         # 对 借款人有利
#                         if ent_benefit == 1:
#                             if amount > 500000 and case_date <= last_year_list[0] and case_date > last_year_list[1]:
#                                 result.append(2)
#                             else:
#                                 result.append(1)
#                         # 对 借款人 不利
#                         elif ent_benefit == 0:
#                             if amount > 1000000:
#                                 if case_date <= last_year_list[-1]:
#                                     result.append(2)
#                                 else:
#                                     result.append(0)
#                             elif amount > 200000 and amount <= 1000000 and important_reason == u'重要案由':
#                                 if case_date <= last_year_list[-1]:
#                                     result.append(1)
#                                 else:
#                                     result.append(0)
#                             elif amount > 200000 and amount <= 1000000 and important_reason == u'一般案由':
#                                 if case_date <= last_year_list[2]:
#                                     result.append(1)
#                                 else:
#                                     result.append(0)
#                             elif amount > 100000 and amount <= 200000 and important_reason == u'重要案由':
#                                 if case_date <= last_year_list[1]:
#                                     result.append(1)
#                                 else:
#                                     result.append(0)
#                             else:
#                                 result.append(1)
#                 except:
#                     result.append(2)
#         if 0 in result:
#             # return u'拒绝'
#             return 0
#         elif 2 in result or None in result:
#             # return u'人工'
#             return 2
#         else:
#             # return u'通过'
#             return 1


def R55_EG_CASE_EntJudicialCheck():
    '''
    公告类型（PTYPE）；16
    立案时间（CASEDATE）；
    被告（PARTY）；
    原告（PLAINTIFF）；
    公告内容（PDESC）；
    案件标题/标的名称（TARGET）；案由（CASEREASON）；案件性质（DOCUCLASS）
    判决结果（JUDGEMENTRESULT）

    公司名称（ENTNAME）；
    :return: 0 拒绝 1 通过 2 人工
    '''
    cpwss_1 = ktggCpwsChecKPre('R227')[0]
    cpwss_2 = ktggCpwsChecKPre('FR227')[0]
    result = ktggCpwsChecKPre('R227')[1] + ktggCpwsChecKPre('FR227')[1]
    if cpwss_1 is None:
        # return u'人工'
        print 'cpws1 为空'
        result.append(2)
    elif cpwss_1 == 1:
        # return u'通过'
        result.append(1)
    else:
        # 司法矩阵 时间节点
        last_year_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(years=i)).strftime('%Y-%m-%d') \
                          for i in [0, 1, 2]]
        last_year_list.append((datetime.datetime.now() - pd.tseries.offsets.DateOffset(months=6)).strftime('%Y-%m-%d'))
        last_year_list = sorted(last_year_list, reverse=True)

        # 对每一条裁判文书 走司法矩阵
        for cpws in cpwss_1:
            lawstatus = cpws.get('LAWSTATUS')
            ent_name = cpws.get('ENTNAME')
            case_date = cpws.get('CASEDATE')
            party = cpws.get('PARTY')
            plaintiff = cpws.get('PLAINTIFF')
            target = cpws.get('TARGET')
            case_reason = cpws.get('CASEREASON')
            doc_class = cpws.get('DOCUCLASS')
            judgement_result = cpws.get('JUDGEMENTRESULT')
            ptype = cpws.get('PTYPE')
            pdesc = cpws.get('PDESC')
            if lawstatus == '无关第三方':
                # result.append(1)
                continue
            # print ent_name, judgement_result
            # 如果其中有一个为空
            if ent_name in null_type_list or case_date in null_type_list or party in null_type_list \
                or party in null_type_list or plaintiff in null_type_list or target in null_type_list \
                or case_reason in null_type_list or doc_class in null_type_list or judgement_result in null_type_list \
                or Formate(case_date) is None or Formate(case_date) > last_year_list[0] or pdesc in null_type_list:
                result.append(None)
            else:
                try:
                    amount = getAmount(entName=ent_name, judgementResult=judgement_result,
                                       ptype=ptype, plaintiff=plaintiff, party=party)

                    important_reason = caseReasonExtraction(casereason=case_reason, pdesc=pdesc, docuclass=doc_class)

                    ent_benefit = benefitExtraction(entName=ent_name, judgementResult=judgement_result,
                                                    plaintiff=plaintiff, party=party)

                    case_settled = caseSettled(judgementResult=judgement_result)

                    print u'测试结果:'
                    print u'金额:',amount,u'重要案由:',important_reason, u'是否有利:',ent_benefit,u'是否结案:',case_settled

                    # ent_benefit== 2 撤诉
                    if ent_benefit == 2:
                        # 通过
                        result.append(1)
                    elif case_settled == u'未结案' or important_reason == u'无法判断' or ent_benefit == -1 or amount is None:
                        # 人工  无法判断
                        result.append(2)
                    else:
                        # 走司法矩阵
                        case_date = Formate(case_date)
                        # 对 借款人有利
                        if ent_benefit == 1:
                            if amount > 500000 and case_date <= last_year_list[0] and case_date > last_year_list[1]:
                                result.append(2)
                            else:
                                result.append(1)
                        # 对 借款人 不利
                        elif ent_benefit == 0:
                            if amount > 1000000:
                                if case_date <= last_year_list[-1]:
                                    result.append(2)
                                else:
                                    result.append(0)
                            elif amount > 200000 and amount <= 1000000 and important_reason == u'重要案由':
                                if case_date <= last_year_list[-1]:
                                    result.append(1)
                                else:
                                    result.append(0)
                            elif amount > 200000 and amount <= 1000000 and important_reason == u'一般案由':
                                if case_date <= last_year_list[2]:
                                    result.append(1)
                                else:
                                    result.append(0)
                            elif amount > 100000 and amount <= 200000 and important_reason == u'重要案由':
                                if case_date <= last_year_list[1]:
                                    result.append(1)
                                else:
                                    result.append(0)
                            else:
                                result.append(1)
                except:
                    result.append(2)
    if cpwss_2 is None:
        # return u'人工'
        print 'cpws2 为空'
        result.append(2)
    elif cpwss_2 == 1:
        # return u'通过'
        result.append(1)
    else:
        # 司法矩阵 时间节点
        last_year_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(years=i)).strftime('%Y-%m-%d') \
                          for i in [0, 1, 2]]
        last_year_list.append((datetime.datetime.now() - pd.tseries.offsets.DateOffset(months=6)).strftime('%Y-%m-%d'))
        last_year_list = sorted(last_year_list, reverse=True)
        # 对每一条裁判文书 走司法矩阵
        for cpws in cpwss_2:
            lawstatus = cpws.get('LAWSTATUS')
            ent_name = cpws.get('ENTNAME')
            case_date = cpws.get('CASEDATE')
            party = cpws.get('PARTY')
            plaintiff = cpws.get('PLAINTIFF')
            target = cpws.get('TARGET')
            case_reason = cpws.get('CASEREASON')
            doc_class = cpws.get('DOCUCLASS')
            judgement_result = cpws.get('JUDGEMENTRESULT')
            ptype = cpws.get('PTYPE')
            pdesc = cpws.get('PDESC')
            if lawstatus == '无关第三方':
                # result.append(1)
                continue
            # print ent_name, judgement_result
            # 如果其中有一个为空
            if ent_name in null_type_list or case_date in null_type_list or party in null_type_list \
                or party in null_type_list or plaintiff in null_type_list or target in null_type_list \
                or case_reason in null_type_list or doc_class in null_type_list or judgement_result in null_type_list \
                or Formate(case_date) is None or Formate(case_date) > last_year_list[0] or pdesc in null_type_list:
                result.append(None)
            else:
                try:
                    amount = getAmount(entName=ent_name, judgementResult=judgement_result,
                                       ptype=ptype, plaintiff=plaintiff, party=party)

                    important_reason = caseReasonExtraction(casereason=case_reason, pdesc=pdesc, docuclass=doc_class)

                    ent_benefit = benefitExtraction(entName=ent_name, judgementResult=judgement_result,
                                                    plaintiff=plaintiff, party=party)

                    case_settled = caseSettled(judgementResult=judgement_result)

                    # print u'测试结果:'
                    # print u'金额:',amount,u'重要案由:',important_reason, u'是否有利:',ent_benefit,u'是否结案:',case_settled
                    # print(pdesc.decode('unicode-escape').encode('utf-8'))
                    # ent_benefit== 2 撤诉
                    if ent_benefit == 2:
                        # 通过
                        result.append(1)

                    elif case_settled == u'未结案' or important_reason == u'无法判断' or ent_benefit == -1 or amount is None:
                        # 人工  无法判断
                        result.append(2)
                    else:
                        # 走司法矩阵
                        case_date = Formate(case_date)
                        # 对 借款人有利
                        if ent_benefit == 1:
                            if amount > 500000 and case_date <= last_year_list[0] and case_date > last_year_list[1]:
                                result.append(2)
                            else:
                                result.append(1)
                        # 对 借款人 不利
                        elif ent_benefit == 0:
                            if amount > 1000000:
                                if case_date <= last_year_list[-1]:
                                    result.append(2)
                                else:
                                    result.append(0)
                            elif amount > 200000 and amount <= 1000000 and important_reason == u'重要案由':
                                if case_date <= last_year_list[-1]:
                                    result.append(1)
                                else:
                                    result.append(0)
                            elif amount > 200000 and amount <= 1000000 and important_reason == u'一般案由':
                                if case_date <= last_year_list[2]:
                                    result.append(1)
                                else:
                                    result.append(0)
                            elif amount > 100000 and amount <= 200000 and important_reason == u'重要案由':
                                if case_date <= last_year_list[1]:
                                    result.append(1)
                                else:
                                    result.append(0)
                            else:
                                result.append(1)
                except:
                    result.append(2)
    if 0 in result:
        # return u'拒绝'
        return 0
    elif 2 in result or None in result:
        # return u'人工'
        return 2
    else:
        # return u'通过'
        return 1

result = R55_EG_CASE_EntJudicialCheck()
# if __name__ == "__main__":
#     import json
#     file_obj = open(r'C:\Users\john\Desktop\samples\case.json', 'r')
#     content = file_obj.read()
#     EG_CASE_DSJ = eval(content)['EG_CASE_DSJ']
#     EG_CASE_DSJ = json.loads(content, encoding='utf-8')
    # aa = R55_EG_CASE_EntJudicialCheck()
    # print aa